<template>
  <div class="leave-management-page">
    <!-- 申请请假按钮 -->
    <el-button type="primary" @click="onLeaveRequestClick">申请请假</el-button>

    <!-- 请假记录表格 -->
    <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="empId" label="员工ID" width="180"></el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="200"></el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="200"></el-table-column>
      <el-table-column prop="type" label="请假类型" width="150"></el-table-column>
      <el-table-column prop="status" label="请假状态" width="150"></el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button
              plain
              type="danger"
              size="small"
              @click="openCancelDialog(scope.row)"
              :disabled="!scope.row.isCancelable">取消请假
          </el-button>
          <el-button
              plain
              type="info"
              size="small"
              @click="viewProcessStatus(scope.row)"
              :disabled="!scope.row.processInstanceId">查看流程
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 申请请假弹框 -->
    <el-dialog :title="modalTitle" v-model="dialogVisible" width="800px" center>
      <el-form :model="form" label-width="100px">
        <el-form-item label="开始时间">
          <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择开始时间" style="width: 100%;"
                          @change="calculateDays"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择结束时间" style="width: 100%;"
                          @change="calculateDays"></el-date-picker>
        </el-form-item>
        <el-form-item label="请假天数">
          <el-input-number v-model="form.days" :min="1" style="width: 100%;" :disabled="true"></el-input-number>
        </el-form-item>
        <el-form-item label="请假类型">
          <el-select v-model="form.type" placeholder="请选择请假类型" style="width: 100%;">
            <el-option label="病假" value="sick"></el-option>
            <el-option label="事假" value="personal"></el-option>
            <el-option label="年假" value="annual"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请假原因">
          <el-input type="textarea" v-model="form.reason" placeholder="请输入请假原因" style="width: 100%;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </div>
    </el-dialog>

    <!-- 取消请假的弹框组件 -->
    <el-dialog title="取消请假" v-model="cancelDialogVisible" width="400px" center>
      <el-input type="textarea" v-model="cancelReason" placeholder="请输入取消请假原因"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCancelLeave">提交</el-button>
      </div>
    </el-dialog>

    <!-- 查看流程弹框组件 -->
    <el-dialog title="请假流程状态" v-model="processStatusDialogVisible" width="600px" center>
      <el-timeline>
        <el-timeline-item
            v-for="(step, index) in processStatus"
            :key="index"
            :timestamp="step.timestamp"
            :color="step.completed ? 'green' : 'gray'">
<!--          {{ step.name }} ({{ step.completed ? '已完成' : '未完成' }}) - {{ step.agreeResult === 'N' ? '驳回' : '通过' }}-->
          {{ step.name }} ({{ step.completed ? '已完成' : '未完成' }}) - {{
            step.completed
                ? (step.agreeResult === 'N' ? '驳回' : '通过')
                : '未通过'
          }}
        </el-timeline-item>
      </el-timeline>
      <div slot="footer" class="dialog-footer">
        <el-button @click="processStatusDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import moment from 'moment';
import {ElMessage} from 'element-plus';

export default {
  name: 'LeaveManagement',
  data() {
    return {
      tableData: [],
      form: {
        startTime: '',
        endTime: '',
        days: 1,
        type: '',
        reason: '',
      },
      modalTitle: '申请请假',
      dialogVisible: false,
      cancelDialogVisible: false, // 控制取消请假的弹框显示
      cancelReason: '', // 存储取消原因
      selectedProcessInstanceId: '', // 存储选中的流程ID
      processStatusDialogVisible: false, // 控制流程状态弹框显示
      processStatus: [] // 存储流程状态数据
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      axios.get('/employeeLeave/findHistoryById').then(res => {
        this.tableData = res.data.data.map(item => {
          const lastTask = item.customTaskList[item.customTaskList.length - 1];
          const leaveDetails = lastTask.details.employeeLeave;
          const isRejected = item.customTaskList.some(task => task.details.agreeResult === 'N');

          return {
            empId: leaveDetails.empId,
            startTime: moment(leaveDetails.startTime).format('YYYY-MM-DD HH:mm:ss'),
            endTime: moment(leaveDetails.endTime).format('YYYY-MM-DD HH:mm:ss'),
            type: this.getLeaveType(leaveDetails.type),
            status: isRejected
                ? '被驳回'
                : item.finished ? '已完成' : '待审批',
            processInstanceId: lastTask.processInstanceId,
            isCancelable: !isRejected && !item.finished
          };
        });
      });
    },
    getLeaveType(type) {
      const typeMap = {
        sick: '病假',
        personal: '事假',
        annual: '年假',
        other: '其他',
      };
      return typeMap[type] || '未知类型';
    },

    onLeaveRequestClick() {
      this.modalTitle = '申请请假';
      this.resetForm();
      this.dialogVisible = true;
    },

    openCancelDialog(row) {
      if (row.status !== '已完成') {  // 判断请假状态
        this.selectedProcessInstanceId = row.processInstanceId; // 存储选中的流程ID
        this.cancelDialogVisible = true; // 显示取消请假的弹框
      }
    },

    submitCancelLeave() {
      axios.post('/employeeLeave/cancel', {
        pid: this.selectedProcessInstanceId, // 传递流程ID
        reason: this.cancelReason,
      }).then(res => {
        if (res.data.code === 200) {
          ElMessage({
            message: '取消请假成功',
            type: 'success',
            duration: 3000,
          });
          this.cancelDialogVisible = false;
          this.cancelReason = ''; // 重置取消原因
          this.fetchData(); // 重新获取数据以更新表格
        } else {
          ElMessage({
            message: '取消请假失败，请重试',
            type: 'error',
            duration: 3000,
          });
        }
      });
    },

    onSubmit() {
      console.log("aaa")
      axios.post('/employeeLeave/apply', this.form).then((res) => {
        if (res.data.code === 200) {
          this.dialogVisible = false;
          this.resetForm();
          ElMessage({
            message: '提交请假成功，等待审核。。',
            type: 'success',
            duration: 3000,
          });
          this.fetchData();
        } else {
          ElMessage({
            message: '提交请假失败，请重新提交。。',
            type: 'error',
            duration: 3000,
          });
        }
      });
    },

    resetForm() {
      this.form = {
        startTime: '',
        endTime: '',
        days: 1,
        type: '',
        reason: '',
      };
    },

    calculateDays() {
      if (this.form.startTime && this.form.endTime) {
        const start = moment(this.form.startTime);
        const end = moment(this.form.endTime);
        const days = end.diff(start, 'days', true);
        this.form.days = Math.ceil(days);
      } else {
        this.form.days = 1;
      }
    },
    viewProcessStatus(row) {
      axios.get(`/employeeLeave/getProcessStatus/${row.processInstanceId}`).then(res => {
        if (res.data.code === 200) {
          this.processStatus = res.data.data.map(step => ({
            name: step.name,
            timestamp: moment(step.timestamp).format('YYYY-MM-DD HH:mm:ss'),
            completed: step.completed,
            agreeResult: step.agreeResult
          }));
          this.processStatusDialogVisible = true;
        } else {
          ElMessage({
            message: '获取流程状态失败，请重试',
            type: 'error',
            duration: 3000,
          });
        }
      });
    }







  },
};
</script>

<style scoped>
.leave-management-page {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}

/* Ensure styles apply to el-dialog */
:deep(.el-dialog) {
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  max-width: 90% !important;
  max-height: 80vh !important;
}

/* Center the dialog body content */
:deep(.el-dialog__body) {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

/* Ensure the dialog header is centered */
:deep(.el-dialog__header) {
  text-align: center;
}

:deep(.el-dialog__body .el-form) {
  width: 100%;
}

:deep(.el-dialog__body .el-form-item) {
  margin-bottom: 20px;
}
</style>
